package com.zyx.mall.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyx.mall.entity.Product;
import com.zyx.mall.entity.queryObject.ProductQuery;
import com.zyx.mall.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 商品
 * </p>
 *
 * @author zyx
 * @since 2023-01-03
 */
@RestController
@RequestMapping("/api/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    //添加商品
    @PostMapping("/add")
    public Boolean addProduct(@RequestBody Product product) {
        return productService.save(product);
    }

    //删除商品
    @DeleteMapping("/del")
    public Boolean delProduct(String id) {
        return productService.removeById(id);
    }

    //修改商品
    @PutMapping("/update")
    public Boolean updateProduct(@RequestBody Product product) {
        return productService.updateById(product);
    }

    //根据商品id查询商品数据
    @GetMapping("/getById")
    public Product getById(String id) {
        return productService.getById(id);
    }

    //带条件的分页查询
    @GetMapping("/list")
    public Page getList(ProductQuery productQuery, Integer currentPage, Integer pageSize) {
        Page<Product> page = new Page<>(currentPage, pageSize);
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq(productQuery.getId() != null && productQuery.getId() != "", "id", productQuery.getId())
                .eq(productQuery.getCategoryId() != null && productQuery.getCategoryId() != "", "category_id", productQuery.getCategoryId())
                .like(productQuery.getName() != null && productQuery.getName() != "", "name", productQuery.getName())
                .orderByDesc("sort");
        productService.page(page, wrapper);
        return page;
    }

    //根据分类id查询商品数据
    @GetMapping("/get")
    public List<Product> getByCondition(ProductQuery productQuery) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq(productQuery.getId() != null && productQuery.getId() != "", "id", productQuery.getId())
                .eq(productQuery.getCategoryId() != null && productQuery.getCategoryId() != "", "category_id", productQuery.getCategoryId())
                .like(productQuery.getName() != null && productQuery.getName() != "", "name", productQuery.getName());

        List<Product> products = productService.list(wrapper);
        return products;
    }

}

